$(function (){
    $("#dataTable").bootstrapTable({
        url:getServerPath()+"system/sys-user/page?pageNo=1&pageSize=10",
        pagination:true,
        pageSize:10,
        pageList:[2,4,8,10],
        //是否隔行变色
        striped:true,
        toolbar: '#toolbar',                //工具按钮用哪个容器
        sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber:1,                       //初始化加载第一页，默认第一页
        search: true,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        showRefresh: true,                  //是否显示刷新按钮
        responseHandler:function(data){
          return data.data.records
        },
        columns:[
            {checkbox: true},
            {field:"id",title:"id",align:"center"},
            {field:"userName",title:"账号",align:"center"},
            {field:"userNickName",title:"名称",align:"center"},
            {field:"sex",title:"性别",align:"center"},
            {field:"birthdayTime",title:"生日",align:"center"},
            {field:"phone",title:"电话",align:"center",width:"150px"},
            {field:"emailAddress",title:"邮箱",align:"center"},
            {field:"status",title:"状态",align:"center"},
            {title:"操作",width:"120px",
                formatter:function (value,row,index){
                    UserName = row.userName;
                    return "   <button type='button' class='btn btn-primary' onclick=queryRole('"+row.userName+"')>\n" +
                        "       <i class='fa fa-tasks'></i>" +
                        "       分配权限\n" +
                        "    </button>"
                }
            }
        ]
    })

    $("[name=addUser]").click(function () {
        $("#addUser").modal('show')
    })
    $("[name=updateUser]").click(function () {
        var options = $("#dataTable").bootstrapTable('getSelections') ;
        if(options.length != 1){
            parent.layer.alert("请选择一行数据！", {
                skin: 'layui-layer-molv', //样式类名
                shift: 6 ,//动画类型
                icon:5
            });
            return false
        }

        loadData(options[0])
        $("[name=userPassword]").val("")
        $("#addUser").modal('show')

    })

    $("[name=save]").click(function () {
        var dataObj = {};
        $.each($("#addInfoForm").serializeArray(),function () {
            dataObj[this.name] = this.value
        })
        if(dataObj.id == ""){
            var data = request("post","system/sys-user/add?roleId=1",dataObj)
            if(data.code != 200){
                parent.layer.alert(data.message, {
                    skin: 'layui-layer-molv', //样式类名
                    shift: 6 ,//动画类型
                    icon:5
                });
                return false
            }
            $(':input','#addInfoForm').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
            $("#dataTable").bootstrapTable("refresh",data.data.records);
            $("#addUser").modal('hide')
            parent.layer.alert(data.data, {
                skin: 'layui-layer-molv', //样式类名
                shift: 1 ,//动画类型
                icon:1
            });
            return false
        }
        var data = request("put","system/sys-user/update",dataObj)
        if(data.code != 200){
            parent.layer.alert(data.message, {
                skin: 'layui-layer-molv', //样式类名
                shift: 6 ,//动画类型
                icon:5
            });
            return false
        }
        $(':input','#addInfoForm').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
        $("#dataTable").bootstrapTable("refresh",data.data.records);
        $("#addUser").modal('hide')
        parent.layer.alert(data.data, {
            skin: 'layui-layer-molv', //样式类名
            shift: 1 ,//动画类型
            icon:1
        });

    })

    $("[name=updateRole]").click(function () {
        var dataObj = new Object();
        dataObj.userName = username;
        var data = request("put","system/sys-user/updateUserRole?roleId="+$("input[name='role']:checked").val(),dataObj)
        if(data.code != 200){
            parent.layer.alert(data.message, {
                skin: 'layui-layer-molv', //样式类名
                shift: 6 ,//动画类型
                icon:5
            });
            return false
        }
        parent.layer.alert(data.data, {
            skin: 'layui-layer-molv', //样式类名
            shift: 1 ,//动画类型
            icon:1
        });
        $("#roleModal").modal('hide')
    })

    $("[name=delete]").click(function () {
        var options = $("#dataTable").bootstrapTable('getSelections') ;
        if(options.length == 0){
            parent.layer.alert("请至少选择一行数据！", {
                skin: 'layui-layer-molv', //样式类名
                shift: 6 ,//动画类型
                icon:5
            });
            return false
        }
        var ids = ""
        for(var i = 0;i < options.length;i++){
            ids = ids + options[i].id+",";
        }
        var data = request("delete","system/sys-user/delete?ids="+ids,"")
        if(data.code != 200){
            parent.layer.alert(data.message, {
                skin: 'layui-layer-molv', //样式类名
                shift: 6 ,//动画类型
                icon:5
            });
            return false
        }
        $("#dataTable").bootstrapTable("refresh",data.data.records);
        parent.layer.alert(data.data, {
            skin: 'layui-layer-molv', //样式类名
            shift: 1 ,//动画类型
            icon:1
        });
    })





    var data = request("get","system/sys-user/queryList","")
    if(data.code != 200){
        parent.layer.alert(data.message, {
            skin: 'layui-layer-molv', //样式类名
            shift: 6 ,//动画类型
            icon:5
        });
        return false
    }
    var html = "";
    $.each(data.data,function () {
        html = html + "<label>" +
            "               <input type='radio' name='role' id='"+this.id+"' value='"+this.id+"'>\n" +
            "               " +this.roleName
        "           </label>"
    })
    $("#radio").html(html);

})
var username = ""
function queryRole(id) {
    username = id;
    var data = request("get","system/sys-user/queryUserNameRoleId?username="+id,"")

    console.log(data)
    $('#'+data.data.roleId).attr('checked', 'checked');
    $("#roleModal").modal('show')
}


function loadData(jsonStr){
    var obj = jsonStr;
    var key,value,tagName,type,arr;
    for(x in obj){
        key = x;
        value = obj[x];
        $("[name='"+key+"'],[name='"+key+"[]']").each(function(){
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            if(tagName=='INPUT'){
                if(type=='radio'){
                    $(this).attr('checked',$(this).val()==value);
                }else if(type=='checkbox'){
                    arr = value.split(',');
                    for(var i =0;i<arr.length;i++){
                        if($(this).val()==arr[i]){
                            $(this).attr('checked',true);
                            break;
                        }
                    }
                }else{
                    $(this).val(value);
                }
            }else if(tagName=='SELECT' || tagName=='TEXTAREA'){
                $(this).val(value);
            }

        });
    }
}

//暂时不用
function loadForm(json,formId) {
    var serializeArray = $("#" + formId).serializeArray();
    for (var i = 0; i < serializeArray.length; i++) {
        var name = serializeArray[i].name;
        if (json[name]) {
            var value = json[name];
            $("[name='" + name + "']").val(value);
        }
    }
}